import React, { Component } from 'react'
import { Table, Checkbox, Icon, Modal, Button, Input, Select, message, Tooltip } from 'antd'
import { axios } from '../../Utils/index'
import moment from 'moment'
import cookie from 'js-cookie'
import locale from 'antd/es/locale/zh_CN'
import 'moment/locale/zh-cn'
import iscroll from 'iscroll'
import { Array } from 'core-js'
moment.locale('zh-cn')


const { confirm } = Modal
const { Option } = Select


export default class HomeTable extends Component {
    constructor (props) {
        super(props)

        this.state = {
            tabs: ['产品表现', '指标评价', '风格评价'],
            visible: false,
            attentionColumns: false,
            dataSource: this.props.dataSource,
            currentPage: this.props.currentPage,
            tempAttentions: [],
            loading: true,
            fundValue: 'fundNav',
            openStatus: false,
            rateStatus: false,
            rateValue: 'year',
            marketValue: 'selectValue',
            marketStatus: false,
            pageSize: this.props.pageSize,
            stroageId: window.sessionStorage.getItem('stroageId') ? window.sessionStorage.getItem('stroageId') : [],
            columns: [
                {
                    title: () => {
                        return (<span href='/'>关注</span>)
                    },
                    dataIndex: 'attentions',
                    key: '1',
                    width: 60,
                    fixed: 'left',
                    render: (t, r) => {
                        let id = r.fundId
                        if (r.isFav === 0) {
                            return (<span data-id={`${id}`} id={`${id}`} className={`iconfont iconguanzhu heart_check`} onClick={this.headerCheck.bind(this)} />)
                        } else {
                            return (<span data-id={`${id}`} id={`${id}`} className={`iconfont iconyiguanzhu heart_check`} onClick={this.headerCheck.bind(this)} />)
                        }
                    }
                },
                {
                    title: '对比',
                    dataIndex: 'compare',
                    key: '2',
                    width: 60,
                    fixed: 'left',
                    render: (t, r) => {
                        const status = this.state.stroageId.indexOf(`${r['fundId']}`) !== -1 ? true : false
                        return (<Checkbox checked={status} id={`${r['fundId']}`} name={r['fundName']} onChange={this.changes}></Checkbox>)
                    }
                },
                {
                    title: '序号',
                    dataIndex: 'key',
                    width: 80,
                    fixed: 'left',
                    key: '3',
                    render: (text) => (<span>{text!== '' ? text : '--'}</span>)
                },
                {
                    title: '产品名称',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    dataIndex: 'fundName',
                    key: '4',
                    ellipsis: true,
                    render: (text, recoder) => (<Tooltip placement="bottom" title={text}>
                        {text ?
                        <a className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/product?id=${recoder.fundId}&name=${encodeURI(text)}`}>{text ? text : '--'}</a>
                        : <span>{text ? text : '--'}</span>
                        }
                        </Tooltip>)
                },
                {
                    title: '投资顾问',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    dataIndex: 'fundConsultant',
                    key: '5',
                    ellipsis: true,
                    render: (text, recoder) => {
                    let results = ``
                    if (text) {
                        results = <a  className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/advisor?id=${recoder.orgId}`}>{text ? text : '--'}</a>
                    } else {
                        results = <span className='table_color table_href'>{text ? text : '--'}</span>
                    }
                    return results
                    }
                },

                {
                    title: '投资经理',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    dataIndex: 'fundManager',
                    key: '6',
                    ellipsis: true,
                    render: (text, recoder) => {
                        let results = ``
                        if (text) {
                            results = <a className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/manager?id=${recoder.fundManagerId}`}>{text ? text : '--'}</a>
                        } else {
                            results = <span className='table_color table_href'>{text ? text : '--'}</span>
                        }
                        return results
                    }
                },
                {
                    title: '资产类别',
                    sorter: true,
                    key: '7',
                    dataIndex: 'assetType',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text ? text : '--'
                        return (<span>{content}</span>)
                    }
                },
                {
                    title: '投资策略',
                    sorter: true,
                    key: '8',
                    dataIndex: 'strategyType',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text ? text : '--'
                        return (<span>{content}</span>)
                    }
                },
                {
                    title: '成立日期',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '9',
                    dataIndex: 'fundFoundationDate',
                    render: text => (<span>{text ? moment(new Date(text)).format('YYYY-MM-DD') : '--'}</span>)
                },
                {
                    title: '最新净值日期',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '18',
                    dataIndex: 'newNavDate',
                    render: text => (<span>{text ? moment(new Date(text)).format('YYYY-MM-DD') : '--'}</span>)
                },
                {
                    title: '产品星级',
                    sorter: true,
                    key: '10',
                    dataIndex: 'fundStar',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text === undefined ? 0 : text
                        let renderStar = []
                        for (let i = 0; i < 5; i++) {
                            if (i < content) {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji icon_color_star`}></span>)
                            } else {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji`}></span>)
                            }
                        }

                        return (renderStar)
                    }
                },
                {
                    title: '投顾星级',
                    sorter: true,
                    key: '11',
                    dataIndex: 'consultantStar',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text === undefined ? 0 : text
                        let renderStar = []
                        for (let i = 0; i < 5; i++) {
                            if (i < content) {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji icon_color_star`}></span>)
                            } else {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji`}></span>)
                            }
                        }

                        return (renderStar)
                    }
                },
                {
                    title:  '累计净值',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '12',
                    className: 'fund_nav_filters',
                    dataIndex: 'fundNav',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                    return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(4)}`}</span>)
                    }
                },
                {
                    title: () => (
                    <div className='home_table_rate'>
                        <span>收益率</span>
                        <Select
                        id='rateSelection'
                        value={this.state.rateValue}
                        open={this.state.rateStatus}
                        onChange={this.fundInto}>
                        <Option className={'rate_select_options'} value="year">今年以来</Option>
                        <Option className={'rate_select_options'} value="m1">近一月</Option>
                        <Option className={'rate_select_options'} value="m3">近三月</Option>
                        <Option className={'rate_select_options'} value="m6">近六月</Option>
                        <Option className={'rate_select_options'} value="y1">近一年</Option>
                        <Option className={'rate_select_options'} value="y2">近二年</Option>
                        <Option className={'rate_select_options'} value="y3">近三年</Option>
                        <Option className={'rate_select_options'} value="total">成立以来年化</Option>
                        </Select>
                    </div>
                ),
                    sorter: true,
                    key: '13',
                    dataIndex: 'nReturn',
                    sortDirections: ['descend', 'ascend'],
                    onClick: (event) => {console.log(event)},
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span className={content > 0 ? 'color_number_red' : 'color_number_green'}>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)+'%'}`}</span>)
                    }
                },
                {
                    title: () => {
                        return (<div className='home_table_rate'>
                            <span>排名</span>
                            <Select
                             id='selectMarket'
                             value={this.state.marketValue}
                             open={this.state.marketStatus}>
                            <Option className={'market_options'} value="selectValue">同策略</Option>
                            <Option className={'market_options'} value="marketValue">全市场</Option>
                            </Select></div>)
                    },
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '14',
                    dataIndex: 'cRank',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span>{content}</span>)
                    }
                },
                {
                    title: '最大回撤',
                    sorter: true,
                    key: '15',
                    dataIndex: 'maxDrawdown',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span className={content > 0 ? 'color_number_red' : 'color_number_green'}>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)}`}</span>)
                    }
                },
                {
                    title: 'Sharpe比率',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '16',
                    dataIndex: 'sharpeA',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)}`}</span>)
                    }
                },
                {
                    title: '信息比率',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '17',
                    dataIndex: 'infoA',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)}`}</span>)
                    }
                }
            ]
        }
    }


    changeSize = (current, size) => {
        const find_c_rank_type = this.state.rateValue === 'selectValue' ? 1 : 2
        const find_c_interval = this.state.rateValue
        // console.log('条数改变了')
        axios(window.__LOADING__)({
            method: 'POST',
            url: '/api/hszcpz/index/selectByScreen',
            data: JSON.stringify({
                ...this.props.searchParams,
                pageSize: size,
                pageNo: current,
                find_c_rank_type: find_c_rank_type,
                find_c_interval: find_c_interval,
                token: cookie.get('token')
            })}
          )
          .then(data => {
              message.destroy()
              this.setState({pageSize: size})
              if (data.status !== 'success') {
                  message.info(data.errorReason)
                  return
              }
              data = JSON.parse(data.result)

              if (data.result === 'success') {
                  let dataList = data.sumlist
                  console.log(data.sumlist)
                  for (let i = 0; i < dataList.length; i++) {
                      dataList[i].key = i + ((current - 1) * size) + 1
                  }
                  this.setState({
                      dataSource: dataList,
                      totalPage: data.pageCount
                    })
                  return this.props.getTableData(dataList, data.sumCount, data.takeDate, current, find_c_rank_type, find_c_interval)
              } else {
                window.__LOADING__(false)
                  if (data.code !== '200') {
                    message.info(data.errMsg)
                  } else {
                    message.info('获取数据失败')
                  }
              }
          })
    }


    changes = (e) => {
        this.props.attetionParent(e.target.id, e.target.name, e.target.checked)
        this.setState({stroageId: window.sessionStorage.getItem('stroageId')})
    }

    updateStorageId = () => {
        this.setState({stroageId: window.sessionStorage.getItem('stroageId')})
    }



    headerCheck = (e) => {
        let _this = this
        let status = e.target.getAttribute('class')
        let id = e.target.getAttribute('data-id')
        const element = e.target
        if (status.indexOf('iconguanzhu') !== -1) {
            const target = e.target
            this.addGroup(id, target)
        } else {
            confirm({
                title: '取消关注',
                content: '您确定要取消关注本产品吗？',
                okText: '确定',
                centered: true,
                cancelText: '取消',
                onOk: () => {
                    axios({
                        method: 'POST',
                        url: '/api/hszcpz/attention/delAttention',
                        data: JSON.stringify({
                            "token": cookie.get('token'),
                            "fgroup_id":"1003",
                            "fav_object_id": id
                        })}
                    )
                    .then(data => {
                        document.getElementById(id).setAttribute('class', 'iconfont iconguanzhu heart_check')
                        if (data.status !== 'success') {
                            message.info(data.errorReason)
                            return
                        }
                        data = JSON.parse(data.result)

                        if (data.result === 'success') {
                            element.setAttribute('class', 'iconfont iconguanzhu heart_check')
                            _this.setState({visible: false})
                        } else {
                            message.destroy()
                            message.error(data.reason)
                        }
                    })
                },
                onCancel () {}
            })
        }

    }

    cancelModal = () => {
        this.setState({visible: false})
    }

    newsGroup = () => {
        this.setState({attentionColumns: true})
    }

    addGroup = (e, target) => {

        axios({
            method: 'POST',
            url: '/api/hszcpz/attention/addAttention',
            data: JSON.stringify({
                "token": cookie.get('token'),
                "fgroup_id":"1003",
                "fav_object_id": e
            })}
        )
        .then(data => {
            message.destroy()
            if (data.status !== 'success') {
                message.info(data.errorReason)
                return
            }
            data = JSON.parse(data.result)

            if (data.result === 'success') {
                target.setAttribute('class', 'iconfont heart_check iconyiguanzhu')
                this.setState({visible: false})
                message.success(data.reason)
            } else {
                message.error(data.reason)
            }
        })

    }

    tableChange = (pagination, filter, sorter, e) => {
        const { current, pageSize } = pagination
        let sorterItem = `${sorter.field}Sort`
        let sortList = {descend: 'desc', ascend: 'asc'}
        const orderIt = sorter.order
        const searchParams = this.props.searchParams
        const find_c_rank_type = this.state.rateValue === 'selectValue' ? 1 : 2
        const find_c_interval = this.state.rateValue
        console.log('页码改变了')
        axios(window.__LOADING__)({
            method: 'POST',
            url: '/api/hszcpz/index/selectByScreen',
            data: JSON.stringify({
                ...searchParams,
                pageSize: pageSize,
                pageNo: current,
                find_c_rank_type: this.state.rateValue === 'selectValue' ? 1 : 2,
                find_c_interval: this.state.rateValue,
                [sorterItem]: sortList[orderIt],
                token: cookie.get('token')
            })}
          )
          .then(data => {
              message.destroy()
              this.setState({pageSize: pageSize})
              if (data.status !== 'success') {
                  message.info(data.errorReason)
                  return
              }
              data = JSON.parse(data.result)

              if (data.result === 'success') {
                  let dataList = data.sumlist
                  for (let i = 0; i < dataList.length; i++) {
                      dataList[i].key = i + ((current - 1) * pageSize) + 1
                  }
                  this.setState({
                      dataSource: dataList,
                      totalPage: data.pageCount
                    })
                  return this.props.getTableData(dataList, data.sumCount, data.takeDate, current, find_c_rank_type, find_c_interval)
              } else {
                window.__LOADING__(false)
                if (data.code !== '200') {
                    message.info(data.errMsg || '获取数据失败')
                } else {
                    message.info('获取数据失败')
                }
              }
          })

    }


    stopRate = (e) => {
        const checkOptions = {'成立以来年化': 'total', '今年以来': 'year', '近一月': 'm1', '近三月': 'm3', '近六月': 'm6', '近一年': 'y1', '近二年': 'y2', '近三年': 'y3'}
        e.stopPropagation()
        const value = checkOptions[e.target.innerHTML]
        this.setState({rateStatus: false, rateValue: value})
        const size = this.state.pageSize
        const page = this.state.currentPage
        const searchParams = this.props.searchParams
        const find_c_rank_type = this.state.rateValue === 'selectValue' ? 1 : 2
        const find_c_interval = value

        axios(window.__LOADING__)({
            method: 'POST',
            url: '/api/hszcpz/index/selectByScreen',
            data: JSON.stringify({
                ...searchParams,
                pageSize:  size,
                pageNo: page,
                find_c_rank_type: this.state.rateValue === 'selectValue' ? 1 : 2,
                find_c_interval: value,
                token: cookie.get('token')
            })}
          )
          .then(data => {
            //   this.setState({currentPage: page})
              if (data.status !== 'success') {
                  message.info(data.errorReason)
                  return
              }
              data = JSON.parse(data.result)

              if (data.result === 'success') {
                  let dataList = data.sumlist
                  for (let i = 0; i < dataList.length; i++) {
                      dataList[i].key = i + ((page - 1) * size) + 1
                  }
                  this.setState({
                      dataSource: dataList,
                      totalPage: data.pageCount
                    })
                    return this.props.getTableData(dataList, data.sumCount, data.takeDate, page, find_c_rank_type, find_c_interval)
              } else {
                window.__LOADING__(false)
                  if (data.errMsg) {
                    message.info(data.errMsg)
                  } else {
                    message.info('获取数据失败')
                  }
              }
          })
    }


    stopMarket = (e) => {
        const checkOptions = {'同策略': 'selectValue', '全市场': 'marketValue'}
        e.stopPropagation()
        console.log(this.state)

        const value = checkOptions[e.target.innerHTML]
        this.setState({marketStatus: false, marketValue: value})
        const size = this.state.pageSize
        const page = this.state.currentPage
        const searchParams = this.props.searchParams
        const findRate = value === 'selectValue' ? 1 : 2
        const find_c_rank_type = findRate
        const find_c_interval = this.state.rateValue

        axios(window.__LOADING__)({
            method: 'POST',
            url: '/api/hszcpz/index/selectByScreen',
            data: JSON.stringify({
                ...searchParams,
                pageSize:  size,
                pageNo: page,
                find_c_interval: find_c_interval,
                find_c_rank_type: findRate,
                token: cookie.get('token')
            })}
          )
          .then(data => {
            //   this.setState({currentPage: page})
              if (data.status !== 'success') {
                  message.info(data.errorReason)
                  return
              }
              data = JSON.parse(data.result)

              if (data.result === 'success') {
                  let dataList = data.sumlist
                //   console.log(data.sumlist)
                  for (let i = 0; i < dataList.length; i++) {
                      dataList[i].key = i + ((page - 1) * size) + 1
                  }
                  this.setState({
                      dataSource: dataList,
                      totalPage: data.pageCount
                    })
                    return this.props.getTableData(dataList, data.sumCount, data.takeDate, page, find_c_rank_type, find_c_interval)
              } else {
                  window.__LOADING__(false)
                  if (data.errMsg) {
                    message.info(data.errMsg)
                  } else {
                    message.info('获取数据失败')
                  }
              }
          })
    }



    // Component Did mount
    componentDidMount () {
        window.updateStorage = this.updateStorageId
        const rateEle = document.getElementById('rateSelection')
        const marketEle = document.getElementById('selectMarket')

        // 收益率 筛选选择框
        rateEle.addEventListener('click', (e) => {
            e.stopPropagation()
            this.setState({rateStatus: !this.state.rateStatus})
            const list = document.querySelectorAll('.rate_select_options')
            Array.from(list).forEach(item => {
                item.addEventListener('click', this.stopRate, false)
            })
        }, false)

        // 同策略同市场 筛选选择框
        marketEle.addEventListener('click', (e) => {
            e.stopPropagation()
            this.setState({marketStatus: !this.state.marketStatus})
            const list = document.querySelectorAll('.market_options')
            Array.from(list).forEach(item => {
                item.addEventListener('click', this.stopMarket, false)
            })
        }, false)



        ;(() => {
            new iscroll('.ant-table-body', {
                scrollbars: 'custom',
                mouseWheel: false,
                preventDefault: false,
                scrollX: true,
                interactiveScrollbars: true,
                shrinkScrollbars: false,
                bounce: false
            })
        })()

        document.addEventListener('touchmove', function (e) { e.preventDefault(); },false)
        document.addEventListener('click', (e) => {e.stopPropagation(); this.setState({openStatus: false, marketStatus: false, rateStatus: false})}, false)
    }


    render () {
        const { dataSource, totalPage, takeDate, sumCount, currentPage } = this.props || []
        const { columns, pageSize } = this.state

        return (
            <div id={'ibarTest'}>
                <Table id={'homePage_table'}
                style={{marginTop: '30px'}}
                locale={locale}
                dataSource={dataSource}
                columns={columns}
                loading={this.props.loading}
                onChange={this.tableChange.bind(this)}
                pagination={{ showSizeChanger: true,
                showQuickJumper: true,
                current: currentPage,
                pageSizeOptions: ['10', '20', '50', '100'],
                pageSize: pageSize,
                onShowSizeChange: this.changeSize,
                total: (totalPage * 20),
                showTotal: (total) => <span className={'table_data_total'}>共<i className={'color_red total_data_size'}>{dataSource.length > 0 ? sumCount || total: '0'}</i>条数据 <strong>更新日期： <i>{moment(takeDate).format('YYYY-MM-DD')}</i></strong></span> }} scroll={{x: 16 * 140}} />
                <Modal
                title={null}
                okText='添加'
                cancelText='返回'
                onCancel={() => {this.cancelModal()}}
                onOk={() => {this.cancelModal()}}
                centered
                closeIcon=''
                footer={null}
                width='360px'
                visible={this.state.visible}>
                    <div style={{display: this.state.attentionColumns ? 'block' : 'none'}} className='home_attention_wrapper'>
                        <div className='home_attention_tit'><span>添加关注</span></div>
                        <div className='home_attention_content'>
                            <Input placeholder='请输入分组名称' className='home_attention_input' />
                        </div>
                        <div className='home_attention_btns'>
                            <Button onClick={() => {this.cancelModal()}} type='default'>返回</Button>
                            <Button onClick={() => {this.cancelModal()}} type='primary'>添加</Button>
                        </div>
                    </div>
                    <div style={{display: !this.state.attentionColumns ? 'block' : 'none'}} className='home_attention_wrapper'>
                        <div className='home_attention_tit'><span>添加关注</span></div>
                        <div className='home_attention_btns'>
                            <Button className='home_new_group' onClick={this.newsGroup} type='primary'><Icon type='plus' />新增分组</Button>
                        </div>
                        <div className='home_group_list'>
                            <ul>
                                <li className='clear-fix'><span>私募基金</span><Button type='danger' onClick={(event) => {this.addGroup(event)}}>添加</Button></li>
                                <li className='clear-fix'><span>私募基金</span><Button type='danger'>添加</Button></li>
                            </ul>
                        </div>
                    </div>
                </Modal>
            </div>
        )
    }
}
